﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Castle.DynamicProxy;
using System.Reflection;

namespace CommonLib.TransactionHelper
{
    /// <summary>
    /// 事务处理 参考https://www.cnblogs.com/Fengge518/p/14347759.html
    ///
    /// 也可以使用其他的https://github.com/wzl-bxg/NTcc-TransactionCore
    /// </summary>
    public class TransactionScopeAsyncInterCeptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            if (HaveAsyncTrascAttribute(invocation))
            {
                TransactionScope scope = null;
                try
                {
                    scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                    Console.WriteLine("TransactionScopeAsyncFlowOption之前=======");
                    invocation.Proceed();
                    scope.Complete();
                    Console.WriteLine("invocation.Proceed()用户自己的逻辑处理ok=======");
                    Console.WriteLine("TransactionScopeAsyncFlowOption之后=======");
                }
                catch (Exception)
                {
                    Console.WriteLine("TransactionScopeAsyncInterCeptor：发生异常");
                    if (scope != null)
                    {
                        scope.Dispose();
                    }
                }
            }
            else
            {
                Console.WriteLine("没有异步事务发生！");
                invocation.Proceed();
                return;
            }
        }

        private bool HaveAsyncTrascAttribute(IInvocation invocation)
        {
            var methodInfo = invocation.MethodInvocationTarget ?? invocation.Method;
            if (methodInfo.GetCustomAttribute<TransactionScopeAsyncAttribute>() != null)
            {
                return true;
            }
            else { return false; }
        }
    }
}